package module

import (
	"bufio"
	"fmt"
	"gitee.com/liumou_site/logger"
	"os"
	"strconv"
	"strings"
)

// SliceRemoveIndex 通过索引值移除指定元素
func SliceRemoveIndex(l []Record, index int) ([]Record, error) {
	if len(l) > index {
		l = append(l[:index], l[index+1:]...)
		return l, nil
	}
	return l, fmt.Errorf("索引值大于实际值")
}

// Delete 删除HOSTS记录
func (h *Hosts) Delete() {
	reader := bufio.NewReader(os.Stdin)
	for {
		println("请选择需要删除的记录")
		for index, r := range h.RecordList {
			info := fmt.Sprintf("[ %d ] -> [ %s %s ]", index, r.Ip, r.Domain)
			fmt.Println(info)
		}
		fmt.Println("[b] 返回")
		fmt.Println("[q] 退出程序")

		n, _ := reader.ReadString('\n')
		n = strings.TrimSpace(n)
		n = strings.ToLower(n)
		if strings.EqualFold(n, "b") {
			return
		}
		if strings.EqualFold(n, "q") {
			os.Exit(0)
		}
		ni, err := strconv.Atoi(n)
		if err != nil {
			logger.Warn("请输入正确的数字")
			continue
		}
		h.RecordList, err = SliceRemoveIndex(h.RecordList, ni)
		if err != nil {
			logger.Error(err.Error())
			return
		}
		err = h.Write()
		if err != nil {
			logger.Error(err.Error())
			return
		}
		logger.Info("删除成功")
	}

}
